// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
impl Solution {
    pub fn kth_largest_level_sum(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i64 {
          let mut pa = root;
          let mut queue = VecDeque::new();
          let mut arr = Vec::new();
          queue.push_back(pa);
          while(!queue.is_empty()){
              let mut sum:i64=0;
              let size = queue.len();
              for i in 0..size{

                  let node =  queue.pop_front().unwrap();
                  sum += node.val;
                  if node.left.is_some(){
                      queue.push_back(node.left);
                  }
                  if node.right.is_some(){
                      queue.push_back(node.right);
                  }


              }
              arr.push(sum);
          }
          return partition(&arr,0,arr.len()-1,k);
    }

    fn partition(arr:&Vec[i64], left:i64,right:i64,n:i32)->i32{
        let  mid = arr[left];
        
        let mut l =left;
        let mut r = right;
        while( l<r ){
            while(arr[r]>mid&&l<r){
                r -=1;
            }
            if(l<r){
                arr[l] =arr[r];
            }
            while(arr[l]<mid&&l<r){
                l +=1;
            }
            if(l<r){
                arr[r]=arr[l];
            }
        } 
        arr[l] = mid;
        if n==l{
            return arr[l];
        }
        if n>l{
            return partition(arr,l+1,right,n);
        }else{
            return partition(arr,left,l-1);
        }


    }
}